<template>
  <div class="user-form">
    <h2>添加用户</h2>


    <form @submit.prevent="submitUser">
      <div class="form-group">
        <label>用户名：</label>
        <input v-model="user.name" type="text" required/>
      </div>

      <div class="form-group">
        <label>邮箱：</label>
        <input v-model="user.email" type="email" required/>
      </div>

      <button type="submit" :disabled="loading">
        {{ loading ? '提交中...' : '提交' }}
      </button>
    </form>

    <div v-if="successMessage" class="success">{{ successMessage }}</div>

  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: {
        name: '',
        email: '',
      },
      loading: false,
      successMessage: '',
    };
  },
  methods: {
    async submitUser() {
      this.loading = true;
      this.successMessage = '';

      try {
        const response = await axios.post('https://jsonplaceholder.typicode.com/users', this.user);
        this.successMessage = '提交成功！服务器返回数据：' + JSON.stringify(response.data);
        this.user.name = '';
        this.user.email = '';
      } catch (err) {
        alert('提交失败，请查看控制台错误信息');
        console.error(err);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped>
.user-form {
  max-width: 400px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
}

.form-group {
  margin-bottom: 15px;
}

input {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
}

button {
  padding: 10px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  cursor: pointer;
}

button:disabled {
  background-color: #aaa;
}

.success {
  color: green;
  margin-bottom: 15px;
}
</style>